import React, { Component } from "react"
import {
    View,
    Image,
    Text,
    StyleSheet,
    TextInput, TouchableOpacity, Keyboard, ScrollView
} from "react-native"
import navigationhelper from 'src/components/navigationhelper'
import {checkPhone, deviceHeight, deviceWidth, isIPhoneX} from "src/util"
import Layer from "src/components/Layer"
import {inject} from "mobx-react/native"
import { List, InputItem, Flex } from '@ant-design/react-native';
import NavBar from 'src/components/navBar'
import AuthFetch from '../../service/Auth'

@inject('userAuth')
export default class ChangePhoneNum extends Component {
    constructor(props) {

        super(props)
        this.state = {
            oldPhone:this.props.userAuth.currentUser.mobile,
            newPhone:'',
            codeNum:'',
            NewcodeNum:'',
            isFetchingSMSCode:false,
            isNewFetchingSMSCode:false,
            smsText: '获取验证码',
            isClickNext:false,
            newSmsText:'获取验证码',
        }
    }

    fetchUpdateMobile =(newPhone)=>{
        if(!newPhone){
            return Layer.showMsg('请先输入手机号')
        }
        AuthFetch.updateMobile({
            mobile:newPhone,
            sms_code:this.state.codeNum,
            token: this.props.userAuth.token
        }).then((res) => {
            if(res.status == 'success'){
          Layer.showMsg('更改成功,请用新手机号重新登录')
          navigationhelper.push('Login')
          }
        }).catch(function (error) {
            Layer.showMsg(error.message)
        })
    }
    onDone = () => {
        AuthFetch.checkMobile({
            sms_code:this.state.codeNum,
            token: this.props.userAuth.token
        }).then((res) => {
            if(res.status == 'success'){
            this.setState({
                isClickNext:true,
                smsText: '获取验证码',
                isFetchingSMSCode: false,
                isNewFetchingSMSCode: false,
                codeNum:'',
            })
          }
        }).catch(function (error) {
            Layer.showMsg(error.message)
        })
      
    }

    fetchNewSmsCode = (phone) => {
        if(!phone){
            return Layer.showMsg('手机号不能为空')
        }
        this.props.userAuth.getSmsCode({
            mobile:phone
        }).then(() => {
            Layer.showMsg('验证码已发送')
            var timesRun = 0;
            var interval = setInterval(() =>{
                timesRun += 1;
                if(timesRun === 60){
                    this.setState({
                        isNewFetchingSMSCode: false,
                        newSmsText: '获取验证码'

                    })
                    clearInterval(interval)
                    return
                }
                this.setState({
                    isNewFetchingSMSCode: true,
                    newSmsText:`倒计时${(60 -  timesRun)}s`
                })
            }, 1000)
        }).catch(function (error) {
            Layer.showMsg(error.message)
        })
    }
   
    fetchSmsCode = () => {
        AuthFetch.checkCode({
            token: this.props.userAuth.token
        }).then(() => {
            Layer.showMsg('验证码已发送')
            var timesRun = 0;
            var interval = setInterval(() =>{
                timesRun += 1;
                if(timesRun === 60){
                    this.setState({
                        isFetchingSMSCode: false,
                        smsText: '获取验证码'
                    })
                    clearInterval(interval)
                    return
                }
                this.setState({
                    isFetchingSMSCode: true,
                    smsText: `倒计时${(60 - timesRun)}s`
                })
            }, 1000)
        }).catch(function (error) {
            Layer.showMsg(error.message)
        })
    }
   
    render() {
        const {oldPhone,newPhone,codeNum,isClickNext} = this.state
        return (
          <View>
            <NavBar 
            back={()=>{navigationhelper.goBack() }} 
            title={'修改手机号'} 
            leftText={'返回'} 
           />
            <ScrollView>
            <List style={{marginTop:20}}>
         <InputItem
          style={styles.inputItem}
            // clear
            placeholder={isClickNext?'请输入新手机号':''}
            defaultValue={isClickNext?'':oldPhone}
            editable={isClickNext?true:false}
            onChange={value => {
              this.setState({
                newPhone:value
              });
            }}>
         <Text style={styles.leftTextStyle}>{isClickNext?'新手机号':'原手机号'}</Text>  
         </InputItem>

         <InputItem
          style={styles.inputItem}
           placeholder={'请输入验证码'}
           value={codeNum}
           keyboardType="number-pad"
           extra={
               isClickNext?
            <TouchableOpacity
            activeOpacity={0.8}
            style={[styles.codeBack, {backgroundColor:'transparent'}]}
            onPress={()=>{
                if(this.state.newSmsText == '获取验证码'){
                    this.fetchNewSmsCode(newPhone)
                }
                }}>
            <Text
                style={{color:this.state.isNewFetchingSMSCode?'darkgrey':'#ff2121', fontSize: 15, fontFamily: 'PingFang SC'}}>
                {this.state.newSmsText}
            </Text>
             </TouchableOpacity>:

             <TouchableOpacity
            activeOpacity={0.8}
            style={[styles.codeBack, {backgroundColor:'transparent'}]}
            onPress={()=>{
                if(this.state.smsText == '获取验证码'){
                    this.fetchSmsCode()
                }
                }}>
            <Text
                style={{color:this.state.isFetchingSMSCode?'darkgrey' : '#ff2121', fontSize: 15, fontFamily: 'PingFang SC'}}>
                {this.state.smsText}
            </Text>
             </TouchableOpacity>
           }
            onChange={value => {
              this.setState({
                codeNum:value
              });
            }}>
         <Text style={styles.leftTextStyle}>验证码</Text>  
         </InputItem>
        </List>

      {isClickNext?null: <View style={{marginTop:20,borderRadius:5,backgroundColor:'#fff',paddingHorizontal:20,paddingVertical:10,marginHorizontal:15,flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
        <Image
          style={{width:15,height:15}}
          source={require('src/assets/mine/tip.png')}>
        </Image>
        <Text style={{color:'#8E8E93',fontSize:12}}>若原手机号不能正常使用，请联系客服更改手机号</Text>
        </View>
       }
        <Flex justify='center' align='center' style={{marginTop:300,height:50,borderRadius:6,marginHorizontal:20,backgroundColor:'#ff2121'}}
        onPress={()=>{
            isClickNext?this.fetchUpdateMobile(newPhone):this.onDone()
        }}
        >
        <Text style={{color:'#fff',fontSize:16,fontWeight:'bold'}}>{isClickNext?'确定':'下一步'}</Text>
        </Flex>

        </ScrollView>
          </View>

        )
    }
}




const styles = StyleSheet.create({
    container:{
      
    },
    leftTextStyle: {
        color:'#2E2E2E',
        marginLeft:10
      },
      inputItem:{
        fontSize:15,
        marginTop:2,
        marginLeft:20,
      },
      codeBack: {
        width: 81,
        height:24,
        borderRadius: 10,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    }
})